articles

Home / DeveloperSection / Articles / Reentrant Monitor in Java

Reentrant Monitor in Java

Anupam Mishra7345 10-Dec-2015

If you are using more than one synchronized method in the program and want to access both synchronized method in a program on single thread. But problem is that lock is acquire only one synchronized method at a time on single thread. So, we are solving this problem by using Reentrant Monitor.

Reentrant Monitor is a powerful concept to java thread can reuse the same monitor for different synchronized methods if method is called from the method.

It eliminates the possibilities of the single thread deadlocking.

Locks are generally used to protect against concurrent state changes made by other threads.

The downside is that you can't assume that nothing you call will change the state of the variables that the lock is designed to protect. However, that's not usually a problem.

The widely advantage of using reentrant locks is that you don't have to worry about the possibility of failing due to accidentally acquiring a lock that you already hold. 

For example, we are creating two files SyCls and ReentrantEx respectively. In SyCls, we are

Declaring two synchronized method doSomeThing () and doAnotherThing ().one

synchronized method calling to another one in the SyCls class. 

class SyCls { 
    public synchronized void doSomeThing()
{
    doAnotherThing();
    System.out.println("this is
doSomeThing() method");
    }
    public synchronized void doAnotherThing()
{
    System.out.println("this is
doAnotherThing() method");
    }
}
public class ReentrantEx{
public static void main(String
args[]){
final ReentrantEx re=new
ReentrantEx();
Thread t1=new Thread(){
public void run(){
new SyCls().doSomeThing();//calling method of SyCls class
}
};
t1.start();
}}   

 

Reentrant Monitor in Java

Updated 07-Sep-2019

Leave Comment

Comments

Liked By